<template>
  <el-dialog
    v-model="visible"
    :title="$t('shop.withdraw')"
    :close-on-click-modal="false"
    :width="dialogWidth"
    @close="onClose"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      :label-width="labelWidth"
      @submit.prevent
      @keyup.enter="onSubmit()"
    >
      <el-form-item
        :label="$t('shop.storeName') + '：'"
        prop="shopName"
      >
        <span class="shop-name">{{ dataForm.shopName }}</span>
      </el-form-item>
      <el-form-item
        :label="$t('shop.withdraBala') + '：'"
        prop="withdrawalAmount"
      >
        <span class="withdrawalAmount">{{ lang==="en"?($t("admin.dollar")+settledAmount):(settledAmount+'&nbsp;'+$t("admin.dollar")) }}</span>
      </el-form-item>

      <el-form-item
        :label="$t('shop.withdr') +'：'"
        prop="amount"
      >
        <div style="display: flex;">
          <el-input-number
            v-model="dataForm.amount"
            :placeholder="$t('shop.pleEnWithAmo')"
            :disabled="(paySettlementType!==1 && (!settledAmount || settledAmount < 1)) || (paySettlementType===1 && settledAmount < Number(platformWithdrawalSetting.withdrawCashLeast))"
            class="amount-btn"
            controls-position="right"
            style="width: 160px"
            :min="0.00"
            :precision="2"
            @change="onCheckAmount"
          />
          <el-button
            v-if="(paySettlementType!==1 && settledAmount >= 1)||(paySettlementType===1 && settledAmount > Number(platformWithdrawalSetting.withdrawCashLeast))"
            type="primary"
            link
            class="text-btn"
            @click="onAllAmount"
          >
            {{ $t("shop.withdrawAll") }}
          </el-button>
          <span
            v-if="(paySettlementType!==1 && (!settledAmount || settledAmount < 1)) || (paySettlementType===1 && settledAmount < Number(platformWithdrawalSetting.withdrawCashLeast))"
            class="error-tips"
          >
            {{ paySettlementType === 1? $t('allinpay.notSufficientFundsTip1') + platformWithdrawalSetting.withdrawCashLeast + $t('allinpay.notSufficientFundsTip2') : $t("shop.unToTime") }}
          </span>
        </div>
      </el-form-item>

      <el-form-item
        :label="$t('shop.debitCard') + '：'"
        prop="shopBankCardId"
      >
        <div class="bankcard-box">
          <div
            v-for="(item,shopBankCardId) in bankCardList"
            :key="shopBankCardId"
            :class="['bankcard',dataForm.shopBankCardId == item.shopBankCardId?'active':'']"
            @click="onClickCard(item.shopBankCardId)"
          >
            <div
              v-if="paySettlementType!==1"
              class="close-icon"
              @click="onDeleteBankCard(item)"
            >
              ×
            </div>
            <div class="card-num">
              {{ item.cardNo }}<span
                v-if="item.bankCardPro===0"
                class="tip"
              >{{ $t('allinpay.corporateAccount') }}</span>
            </div>
            <div class="card-bottom">
              <div class="card-name">
                {{ item.bankName }}
              </div>
              <div
                v-if="item.isDefault === 1"
                class="default"
              >
                {{ $t("shop.defaultBankCard") }}
              </div>
              <div
                v-if="item.isDefault === 0"
                class="chooseDefault"
                @click="onSetDefault(item.shopBankCardId)"
              >
                {{ $t("shop.setAsDefault") }}
              </div>
            </div>
          </div>
          <div
            v-if="!bankCardList.length"
            style="color:#C0C4CC"
          >
            {{ $t("shop.noData") }}
          </div>
        </div>
      </el-form-item>
      <div
        v-if="bankCardList.length < 5 || (paySettlementType===1 && (cardNumber<10 || legalCardNumber<1))"
        class="add-card"
        :style="'margin-left:'+labelWidth"
      >
        <el-button
          type="primary"
          link
          @click="onAddBankCard"
        >
          {{ $t("shop.addBankCard") }}
        </el-button>
      </div>

      <el-form-item
        :label="$t('shop.smsVerification') + '：'"
        prop="code"
      >
        <div class="verification-box">
          <el-input
            v-model="dataForm.code"
            class="verification-input"
            maxlength="6"
            placeholder
          />
          <div
            :class="['default-btn primary-btn', showCount && isSendCode ? 'disabled-btn' : '']"
            @click="onSendCode"
          >
            {{ $t("shop.getVerificationCode") + (showCount && isSendCode ? count : '') }}
          </div>
        </div>
      </el-form-item>
      <br>
      <div
        v-if="isSendCode && paySettlementType !== 1"
        class="yzm-tips"
      >
        {{ $t("shop.verifySMS") }}：{{ mobile }}，{{ $t("shop.pleaseCheck") }}
      </div>
      <div
        v-if="isSendCode && paySettlementType === 1"
        class="yzm-tips"
      >
        {{ $t('allinpay.captchaPrompt') }}
      </div>

      <el-form-item
        :label="$t('publics.remark') + '：'"
        prop="shopRemarks"
      >
        <el-input
          v-model="dataForm.shopRemarks"

          type="textarea"
          :placeholder="$t('shop.maximumInput')"
          maxlength="60"
          @input="onHandleInput"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t("crud.filter.cancelBtn") }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="onSubmit()"
        >
          {{ $t("crud.filter.submitBtn") }}
        </div>
      </div>
    </template>

    <addBankCardPop
      v-if="showAddCardPop"
      ref="addBankCardPopRef"
      :card-number="cardNumber"
      :legal-card-number="legalCardNumber"
      @refresh-data-list="onGetShopCardList"
    />
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import addBankCardPop from '@/views/modules/shop/shop-info/components/shop-info-account-manage/index.vue'
import { validNoEmptySpace } from '@/utils/validate'
import { Debounce } from '@/utils/debounce.js'

const emit = defineEmits(['refreshDataList', 'refreshDataList'])

const allinpayStore = useAllinpayStore()

const validateShopRemarks = (rule, value, callback) => {
  if (validNoEmptySpace(value)) {
    callback(new Error($t('shopProcess.inputAllSpace')))
  } else {
    callback()
  }
}
const dataRule = reactive({
  settledAmount: [
    { required: true, message: $t('shop.withdrawaEmpty'), trigger: 'blur' }
  ],
  code: [
    { required: true, message: $t('shop.pleaseEnteCode'), trigger: 'blur' }
  ],
  shopBankCardId: [
    { required: true, message: $t('shop.pleSelTheBankCard'), trigger: 'blur' }
  ],
  shopRemarks: [
    { validator: validateShopRemarks, trigger: 'blur' }
  ]
})
const labelWidth = localStorage.getItem('bbcLang') === 'en' ? '170px' : '120px'
const lang = localStorage.getItem('bbcLang')

const paySettlementType = computed(() => {
  return allinpayStore.paySettlementType
})

const dialogWidth = ref('')
const defWidth = localStorage.getItem('bbcLang') === 'en' ? 800 : 700
onMounted(() => {
  dialogWidth.value = onSetDialogWidth(defWidth)
  window.onresize = () => {
    return (() => {
      dialogWidth.value = onSetDialogWidth(defWidth)
    })()
  }
})
const onSetDialogWidth = function (defWidth) {
  const val = document.body.clientWidth
  const def = defWidth || 850 // 默认宽度
  if (val < def) {
    return '97%'
  } else {
    return def + 'px'
  }
}

const visible = ref(false)
const isSendCode = ref(false)
const isFirstSend = ref(true) // 是否首次请求验证码
const init = () => {
  isSendCode.value = false
  visible.value = true
  isFirstSend.value = true
  if (paySettlementType.value === 1) {
    onGetPlatformWithdrawalSetting()
  }
  onGetDataList()
}
/**
 * 输入限制
 */
const dataForm = ref({
  shopName: '',
  shopBankCardId: '', // 当前选择的银行卡id
  amount: 1, // 提现金额
  code: null, // 验证码
  shopRemarks: '' // 备注
})
const onHandleInput = (value) => {
  dataForm.value.shopRemarks = value.replace(/[^a-zA-Z0-9\u4E00-\u9FA5.]/g, '')
}
/**
 * 获取店铺钱包信息
 */
const settledAmount = ref(1) // 全部可提现金额
const onGetDataList = () => {
  http({
    url: http.adornUrl('/shop/withdrawCash/getShopInfo'),
    method: 'get'
  }).then(({ data }) => {
    dataForm.value = data
    dataForm.value.amount = parseFloat(data.amount)
    settledAmount.value = parseFloat(data.amount)
    onGetShopCardList()
  })
}
/**
 * 获取店铺绑定的银行卡
 */
const bankCardList = ref([]) // 银行卡列表
const legalCardNumber = ref(0) // 法人账户数量
const cardNumber = ref(0) // 非法人账户数量
const onGetShopCardList = () => {
  http({
    url: http.adornUrl('/shop/shopBankCard/getShopBankCardList'),
    method: 'get'
  }).then(({ data }) => {
    bankCardList.value = data
    for (let i = 0; i < bankCardList.value.length; i++) {
      if (bankCardList.value[i].isDefault) {
        onClickCard(bankCardList.value[i].shopBankCardId)
      }
      if (bankCardList.value[i].isDefault && i !== 0) {
        const t = bankCardList.value[i]
        bankCardList.value[i] = bankCardList.value[0]
        bankCardList.value[0] = t
        break
      }
    }
    if (paySettlementType.value === 1) {
      legalCardNumber.value = data.filter(item => item.bankCardPro === 0).length
      cardNumber.value = data.length - legalCardNumber.value
    }
    bankCardList.value = data
  })
}
// 获取平台提现设置
const platformWithdrawalSetting = ref({}) // 平台提现设置
const onGetPlatformWithdrawalSetting = () => {
  http({
    url: http.adornUrl('/shop/withdrawCash/getWithdrawCash'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    platformWithdrawalSetting.value = data
  })
}
/**
 * 校验提现金额的格式
 */
const onCheckAmount = () => {
  const re = /([0-9]+\.[0-9]{2})[0-9]*/
  const num = parseFloat(dataForm.value.amount?.toString().replace(re, '$1'))
  if (num < 0) {
    dataForm.value.amount = 0
  } else if (num > settledAmount.value) {
    dataForm.value.amount = settledAmount.value
  } else {
    dataForm.value.amount = num
  }
}
/**
 * 发送验证码
 */
let timer = null
const mobile = ref('')
let currentCard = {} // 当前银行卡
const count = ref(null)
const showCount = ref(null)
let bizOrderNo = '' // 通联提现订单号
const onSendCode = async () => {
  if (isSendCode.value) {
    return
  }
  if (paySettlementType.value === 1 && !currentCard.shopBankCardId) {
    ElMessage({
      message: $t('allinpay.selectBankTip'),
      type: 'error',
      duration: 1000
    })
    return
  }
  if (paySettlementType.value === 1 && !(await onGetMissingInfo())) {
    return
  }
  let request
  if (paySettlementType.value === 1) {
    const data = {
      shopBankCardId: currentCard.shopBankCardId,
      bankCardNo: currentCard.bankCardNo,
      amount: dataForm.value.amount + '' || '0'
    }
    // 首次发送验证码为申请提现，非首次为重新发送验证码
    if (isFirstSend.value) {
      request = http({
        url: http.adornUrl('/shop/withdrawCash/allinpayApply'),
        method: 'post',
        data: http.adornData(data)
      })
    } else {
      data.bizOrderNo = bizOrderNo
      request = http({
        url: http.adornUrl('/shop/withdrawCash/resendPaySms'),
        method: 'post',
        data: http.adornData(data)
      })
    }
  } else {
    request = http({
      url: http.adornUrl('/shop/shopDetail/sendCode'),
      method: 'post',
      data: http.adornData()
    })
  }
  request.then(({ data }) => {
    isSendCode.value = true
    if (isFirstSend.value) {
      isFirstSend.value = false
    }
    // 通联支付接口返回的提现订单号，保存提现订单号
    if (paySettlementType.value === 1) {
      bizOrderNo = data
    } else {
      // 非通联接口返回手机号
      mobile.value = data
    }
    const timeCount = 60
    if (!showCount.value) {
      count.value = timeCount
      showCount.value = true
      timer = setInterval(() => {
        if (count.value > 0 && count.value <= timeCount) {
          count.value--
        } else {
          clearInterval(timer)
          isSendCode.value = false
          showCount.value = false
        }
      }, 1000)
    }
  })
}
// 通联支付根据店铺信息提醒用户缺少的信息
const onGetMissingInfo = () => {
  return new Promise((resolve) => {
    http({
      url: http.adornUrl('/shop/shopDetail/info'),
      method: 'get',
      params: http.adornParams()
    }).then(({ data }) => {
      const tips = []
      if (currentCard.bankCardPro !== 0 && (data.companyAcctProtocolNo === null || data.companyAcctProtocolNo === '')) {
        tips.push($t('allinpay.missingInfoTip1'))
      }
      if (currentCard.bankCardPro !== 1 && (data.legalAcctProtocolNo === null || data.legalAcctProtocolNo === '')) {
        tips.push($t('allinpay.missingInfoTip2'))
      }
      if (data.isBindPhone !== 1) {
        tips.push($t('allinpay.missingInfoTip3'))
      }
      if (data.isCreateMember !== 1) {
        tips.push($t('allinpay.missingInfoTip4'))
      }
      if (data.companyInfoProcessStatus !== 2) {
        tips.push($t('allinpay.missingInfoTip5'))
      }
      if (data.idCardCollectProcessStatus !== 4) {
        tips.push($t('allinpay.missingInfoTip6'))
      }
      if (tips.length > 0) {
        ElMessage({
          message: $t('allinpay.confirmTip') + tips.join('、') + '！',
          type: 'error',
          duration: 1500
        })
        resolve(false)
      }
      resolve(true)
    })
  })
}
/**
 * 设置默认银行卡
 */
const onSetDefault = (shopBankCardId) => {
  http({
    url: http.adornUrl('/shop/shopBankCard/setDefault'),
    method: 'put',
    data: http.adornData({
      shopBankCardId
    })
  }).then(() => {
    onGetShopCardList()
  })
}
/**
 * 选择银行卡
 */
const onClickCard = (cardId) => {
  bankCardList.value.forEach(element => {
    if (element.shopBankCardId === cardId) {
      currentCard = element
    }
  })
  dataForm.value.shopBankCardId = cardId
}
/**
 * 添加银行卡
 */
const addBankCardPopRef = ref(null)
const showAddCardPop = ref(false) // 添加银行卡弹框
const onAddBankCard = () => {
  showAddCardPop.value = true
  nextTick(() => {
    addBankCardPopRef.value?.init()
  })
}
/**
 * 删除银行卡
 */
const onDeleteBankCard = (item) => {
  const cardId = item.shopBankCardId
  if (item.isDefault === 1) {
    ElMessage({
      message: $t('shop.cannotBankCard'),
      type: 'error',
      duration: 1500
    })
    return
  }
  http({
    url: http.adornUrl('/shop/shopBankCard/' + cardId),
    method: 'delete'
  }).then(() => {
    onGetShopCardList()
  })
}
const onClose = () => {
  visible.value = false
  emit('refreshDataList')
}
const onAllAmount = () => {
  dataForm.value.amount = settledAmount.value
}
/**
 * 表单提交
 */
const dataFormRef = ref(null)
const onSubmit = Debounce(() => {
  dataFormRef.value?.validate(valid => {
    if (valid) {
      if (dataForm.value.amount !== 0 && !dataForm.value.amount) {
        ElMessage({
          message: $t('shop.pleEnWithAmo'),
          type: 'error',
          duration: 1500
        })
        return
      }
      let request
      if (paySettlementType.value === 1) {
        const data = {
          bankCardNo: currentCard.bankCardNo,
          amount: (dataForm.value.amount + '') || '0',
          bizOrderNo,
          verificationCode: dataForm.value.code
        }
        request = http({
          url: http.adornUrl('/shop/withdrawCash/confirmWithdrawPay'),
          method: 'post',
          data: http.adornData(data)
        })
      } else {
        request = http({
          url: http.adornUrl('/shop/withdrawCash/apply'),
          method: 'post',
          data: http.adornData(dataForm.value)
        })
      }
      request.then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshDataList')
          }
        })
      })
    }
  })
}, 1500)

defineExpose({
  init
})
</script>

<style lang="scss" scoped>
@use './index.scss';
</style>
